﻿using Microsoft.AspNetCore.SignalR;

namespace WebApi.Filters;

/// <summary>
/// 自定义Hub过滤器
/// </summary>
public class LanguageHubFilter:IHubFilter
{
    private List<string> bannedPhrases = new List<string> { "async","void", ".Result" };

    /// <summary>
    /// 自定义Hub过滤器触发方法
    /// </summary>
    /// <param name="invocationContext"></param>
    /// <param name="next"></param>
    /// <returns></returns>
    public async ValueTask<object?> InvokeMethodAsync(
        HubInvocationContext invocationContext,
        Func<HubInvocationContext, ValueTask<object?>> next)
    {
        var languageFilter = (LanguageFilterAttribute)Attribute.GetCustomAttribute(invocationContext.HubMethod, typeof(LanguageFilterAttribute))!;
        if (languageFilter != null
            && invocationContext.HubMethodArguments.Count>languageFilter.FilterArgument
            && invocationContext.HubMethodArguments[languageFilter.FilterArgument] is string str)
        {
            foreach(var bannedPhrase in bannedPhrases)
            {
                str = str.Replace(bannedPhrase, "****");
            }

            var argument = invocationContext.HubMethodArguments.ToArray();
            argument[languageFilter.FilterArgument] = str;
            invocationContext = new HubInvocationContext(
                invocationContext.Context,
                invocationContext.ServiceProvider,
                invocationContext.Hub,
                invocationContext.HubMethod,
                argument);
        }
        return await next(invocationContext);
    }

}
